﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SqlScriptVault.Model
{
    [Serializable]
    public class ScriptVault
    {
        private readonly SortedList<int, Script> _scripts;
        private readonly SortedList<DateTime, IHistory> _history;
        private bool _hasChanges = false;

        public ScriptVault()
        {
            _scripts = new SortedList<int, Script>();
            _history = new SortedList<DateTime, IHistory>();
        }

        public ICollection<Script> Scripts
        {
            get
            {
                var scripts = (from script in _scripts orderby script.Key select script.Value).ToList();
                return new ReadOnlyCollection<Script>(scripts);
            }
        }

        public ICollection<Script> Executions
        {
            get
            {
                var scripts = (from script in _scripts orderby script.Key select script.Value).ToList();
                return new ReadOnlyCollection<Script>(scripts);
            }
        }

        public ICollection<IHistory> History
        {
            get
            {
                var history = (from entry in _history orderby entry.Key select entry.Value).ToList();
                return new ReadOnlyCollection<IHistory>(history);
            }
        }

        public bool HasChanges
        {
            get
            {
                return _hasChanges;
            }
        }

        public void Add(Script script)
        {
            script.Number = Scripts.Count + 1;
            _scripts.Add(Scripts.Count + 1, script);
            _history.Add(DateTime.Now, new AddFileHistory(script.ScriptName, script.ScriptContent));
            _hasChanges = true;
        }

        public void AddExecution(DateTime dateTime, ScriptVaultExecution scriptVaultExecution)
        {
            _history.Add(dateTime, new ExecutionHistory(scriptVaultExecution));
        }

        public void AddUpdatedFileHistory(string scriptName, string previousScript, string nextScript)
        {
            _history.Add(DateTime.Now, new UpdateFileHistory(scriptName, previousScript, nextScript));
        }

        public void Saved()
        {
            _hasChanges = false;
        }

        public bool ScriptNameExists(string scriptName)
        {
            return _scripts.Any(s => s.Value.ScriptName == scriptName);
        }
    }
}
